package fun.codefarmer.pm.utils.fileUtil;

import fun.codefarmer.pm.constant.Constant;
import fun.codefarmer.pm.dto.UploadDto;
import fun.codefarmer.pm.model.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @Author z
 * @Date 2021/11/27 12:35
 * @Version 1.0
 */
@Component
public class ImagUtils {
    private final ResourceLoader resourceLoader;
    @Value("${web.profile}")
    private String path;

    public ImagUtils(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 单图片上传
     * @param file
     * @return
     */
    public Result<UploadDto> imgUpload(MultipartFile file) {

        if (file.isEmpty()) {
            return new Result<UploadDto>().error("文件不能为空");
        }
        try {
            //1.定义上传的文件
            String localPath = path;
            //2.获得文件名字
            String fileName = file.getOriginalFilename();
            //3.上传

            //3.1 生成新的文件路径和文件名
            String newfilename = FileNameUtils.getFileName(fileName);
//            String realPath =  FileNameUtils.datePath() + File.separator + FileNameUtils.getFileName(fileName);
            String realPath =  FileNameUtils.datePath() + File.separator + newfilename;
            // 保存的文件及文件地址
            String savePath = localPath + File.separator + realPath;
            //3.2 保存文件
            File dest = new File(savePath);
            //判断文件目目录是否存在,不存在则新建
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            // 新增 压缩文件
            PictureUtil.Tosmallerpic(localPath + File.separator+FileNameUtils.datePath(), new File(savePath), newfilename.substring(newfilename.lastIndexOf(".")), newfilename, (float) 0.1);

            //保存路径到数据库
            String url = Constant.RESOURCE_PREFIX + File.separator + realPath;
            UploadDto uploadDto = new UploadDto();
            uploadDto.setFileName(fileName);
            uploadDto.setUrl(url);
            return new Result<UploadDto>().ok(uploadDto);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result<UploadDto>().error("文件上传失败");
        }
    }
}
